<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文档打印系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .drop-zone {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .drop-zone:hover, .drop-zone.dragover {
            border-color: #4f46e5;
            background-color: #f5f3ff;
        }
        .file-item {
            border-bottom: 1px solid #e5e7eb;
            padding: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .file-item:last-child {
            border-bottom: none;
        }
        .status-badge {
            border-radius: 9999px;
            padding: 2px 8px;
            font-size: 12px;
            font-weight: 500;
        }
        .status-uploaded {
            background-color: #dbeafe;
            color: #2563eb;
        }
        .status-printing {
            background-color: #fef3c7;
            color: #d97706;
        }
        .status-printed {
            background-color: #d1fae5;
            color: #059669;
        }
        .status-failed {
            background-color: #fee2e2;
            color: #dc2626;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="max-w-6xl mx-auto px-4 py-8">
        <div class="text-center mb-8">
            <h1 class="text-3xl font-bold text-gray-900 mb-2">文档打印系统</h1>
            <p class="text-gray-600">上传并打印您的文档</p>
        </div>

        <div class="bg-white rounded-lg shadow-md overflow-hidden">
            <div class="p-6">
                <h2 class="text-xl font-semibold text-gray-900 mb-4">上传文件</h2>
                <div id="dropZone" class="drop-zone" 
                     onclick="document.getElementById('fileInput').click()"
                     ondrop="handleDrop(event)" 
                     ondragover="handleDragOver(event)" 
                     ondragleave="handleDragLeave(event)">
                    <input type="file" id="fileInput" class="hidden" onchange="handleFileSelect(event)">
                    <div class="space-y-2">
                        <svg xmlns="http://www.w3.org/2000/svg" class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                        </svg>
                        <p class="text-gray-700">点击或拖放文件到此处上传</p>
                        <p class="text-sm text-gray-500" id="allowedExtensions">正在加载支持的文件类型...</p>
                    </div>
                </div>

                <!-- 文件选择状态 -->
                <div id="fileSelectStatus" class="hidden mt-4">
                    <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                        <div class="flex items-center space-x-4">
                            <div>
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-indigo-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                </svg>
                            </div>
                            <div>
                                <p id="selectedFileName" class="font-medium text-gray-900"></p>
                                <p id="selectedFileSize" class="text-sm text-gray-500"></p>
                            </div>
                        </div>
                        <div class="flex items-center space-x-2">
                            <button onclick="cancelFileSelect()" class="px-3 py-1 text-sm text-gray-600 hover:text-gray-900">
                                取消
                            </button>
                            <button onclick="uploadSelectedFile()" id="uploadButton" class="px-4 py-2 bg-indigo-600 text-white text-sm font-medium rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                上传文件
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 上传状态 -->
                <div id="uploadStatus" class="hidden mt-4"></div>
            </div>
        </div>

        <!-- 文件列表 -->
        <div class="mt-8 bg-white rounded-lg shadow-md overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <div class="flex justify-between items-center">
                    <h2 class="text-xl font-semibold text-gray-900">文件列表</h2>
                    <button onclick="refreshFileList()" class="text-indigo-600 hover:text-indigo-800">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                        </svg>
                    </button>
                </div>
            </div>
            <div id="fileList" class="divide-y divide-gray-200">
                <div class="p-6 text-center text-gray-500">
                    正在加载文件列表...
                </div>
            </div>
        </div>
    </div>

    <script>
        // 页面加载时获取配置和文件列表
        document.addEventListener('DOMContentLoaded', async () => {
            await getConfig();
            refreshFileList();
            // 每30秒自动刷新文件列表
            setInterval(refreshFileList, 30000);
        });

        // 获取服务器配置
        async function getConfig() {
            try {
                const response = await fetch('/config');
                const data = await response.json();
                
                // 显示支持的文件类型
                const extensionsText = document.getElementById('allowedExtensions');
                if (data.allowed_extensions && data.allowed_extensions.length > 0) {
                    extensionsText.textContent = `支持的文件类型: ${data.allowed_extensions.join(', ')}`;
                } else {
                    extensionsText.textContent = '支持的文件类型: 所有文件';
                }
            } catch (error) {
                console.error('获取配置失败:', error);
            }
        }

        // 刷新文件列表
        async function refreshFileList() {
            const fileList = document.getElementById('fileList');
            
            try {
                const response = await fetch('/files');
                const data = await response.json();
                
                if (!data.success) {
                    throw new Error(data.error || '获取文件列表失败');
                }
                
                if (!data.files || data.files.length === 0) {
                    fileList.innerHTML = `
                        <div class="p-6 text-center text-gray-500">
                            暂无文件
                        </div>
                    `;
                    return;
                }
                
                // 按上传时间降序排序
                data.files.sort((a, b) => new Date(b.upload_time) - new Date(a.upload_time));
                
                // 清空列表并添加文件
                fileList.innerHTML = '';
                
                data.files.forEach(file => {
                    const fileItem = document.createElement('div');
                    fileItem.className = 'file-item';
                    
                    // 获取状态样式
                    const statusClass = getStatusClass(file.status);
                    const statusText = getStatusText(file.status);
                    
                    fileItem.innerHTML = `
                        <div class="flex items-center space-x-4">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                            </svg>
                            <div>
                                <p class="font-medium text-gray-900">${file.original_filename}</p>
                                <p class="text-sm text-gray-500">上传时间: ${new Date(file.upload_time).toLocaleString()}</p>
                            </div>
                        </div>
                        <div class="flex items-center space-x-4">
                            <span class="status-badge ${statusClass}">${statusText}</span>
                            ${file.status !== 'printed' ? `
                                <button onclick="showPrintDialog('${file.filename}', '${file.original_filename}')" class="px-3 py-1 text-sm text-white bg-indigo-600 rounded hover:bg-indigo-700">
                                    打印
                                </button>
                            ` : ''}
                        </div>
                    `;
                    
                    fileList.appendChild(fileItem);
                });
                
            } catch (error) {
                console.error('获取文件列表失败:', error);
                fileList.innerHTML = `
                    <div class="p-6 text-center text-red-500">
                        获取文件列表失败: ${error.message}
                    </div>
                `;
            }
        }

        // 获取状态样式类
        function getStatusClass(status) {
            const classes = {
                'uploaded': 'status-uploaded',
                'printing': 'status-printing',
                'printed': 'status-printed',
                'failed': 'status-failed'
            };
            return classes[status] || 'status-uploaded';
        }

        // 获取状态文本
        function getStatusText(status) {
            const texts = {
                'uploaded': '待打印',
                'printing': '打印中',
                'printed': '已打印',
                'failed': '打印失败'
            };
            return texts[status] || '未知状态';
        }

        // 处理文件选择
        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            // 显示文件选择状态
            const fileSelectStatus = document.getElementById('fileSelectStatus');
            const selectedFileName = document.getElementById('selectedFileName');
            const selectedFileSize = document.getElementById('selectedFileSize');
            
            fileSelectStatus.classList.remove('hidden');
            selectedFileName.textContent = file.name;
            selectedFileSize.textContent = formatFileSize(file.size);
            
            // 启用上传按钮
            document.getElementById('uploadButton').disabled = false;
        }

        // 取消文件选择
        function cancelFileSelect() {
            document.getElementById('fileInput').value = '';
            document.getElementById('fileSelectStatus').classList.add('hidden');
            document.getElementById('uploadStatus').classList.add('hidden');
        }

        // 上传选择的文件
        async function uploadSelectedFile() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            
            if (!file) {
                Swal.fire({
                    icon: 'warning',
                    title: '请选择文件',
                    text: '请先选择要上传的文件'
                });
                return;
            }
            
            // 更新按钮状态
            const uploadButton = document.getElementById('uploadButton');
            const originalText = uploadButton.innerHTML;
            uploadButton.disabled = true;
            uploadButton.innerHTML = `
                <svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white inline-block" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                上传中...
            `;
            
            try {
                const formData = new FormData();
                formData.append('file', file);
                
                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // 显示上传成功状态
                    const uploadStatus = document.getElementById('uploadStatus');
                    uploadStatus.classList.remove('hidden');
                    uploadStatus.innerHTML = `
                        <div class="flex items-center justify-between p-4 bg-green-50 rounded-lg">
                            <div class="flex items-center space-x-4">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                                </svg>
                                <div>
                                    <p class="font-medium text-green-800">上传成功: ${file.name}</p>
                                </div>
                            </div>
                            <button onclick="showPrintDialog('${result.filename}', '${result.original_filename}')" class="px-4 py-2 bg-indigo-600 text-white text-sm font-medium rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                打印文件
                            </button>
                        </div>
                    `;
                    
                    // 清空文件选择
                    fileInput.value = '';
                    document.getElementById('fileSelectStatus').classList.add('hidden');
                    uploadButton.disabled = false;
                    uploadButton.innerHTML = originalText;
                    
                    // 刷新文件列表
                    refreshFileList();
                } else {
                    throw new Error(result.message || '上传失败');
                }
            } catch (error) {
                console.error('文件上传错误:', error);
                
                const uploadStatus = document.getElementById('uploadStatus');
                uploadStatus.classList.remove('hidden');
                uploadStatus.innerHTML = `
                    <div class="flex items-center p-4 bg-red-50 rounded-lg">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-red-500 mr-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                        <div>
                            <p class="font-medium text-red-800">上传失败: ${file.name}</p>
                            <p class="text-sm text-red-700">${error.message}</p>
                        </div>
                    </div>
                `;
                
                uploadButton.disabled = false;
                uploadButton.innerHTML = originalText;
            }
        }

        // 显示打印对话框
        async function showPrintDialog(filename, originalFilename) {
            try {
                // 显示加载状态
                Swal.fire({
                    title: '正在获取打印机列表',
                    text: '请稍候...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                // 获取打印机列表
                const response = await fetch('/printers');
                const data = await response.json();
                
                Swal.close();
                
                if (data.error) {
                    // 如果打印服务未运行，提供启动选项
                    if (data.error.includes('打印服务未运行')) {
                        const result = await Swal.fire({
                            icon: 'warning',
                            title: '打印服务未运行',
                            text: '打印服务未运行，是否尝试启动服务？',
                            showCancelButton: true,
                            confirmButtonText: '启动服务',
                            cancelButtonText: '取消'
                        });
                        
                        if (result.isConfirmed) {
                            // 尝试启动打印服务
                            try {
                                await fetch('/start_print_service', {
                                    method: 'POST'
                                });
                                
                                // 服务启动后重试
                                showPrintDialog(filename, originalFilename);
                                return;
                            } catch (err) {
                                Swal.fire({
                                    icon: 'error',
                                    title: '启动服务失败',
                                    text: '无法启动打印服务，请尝试手动启动或联系管理员。'
                                });
                                return;
                            }
                        } else {
                            return;
                        }
                    } else {
                        // 其他错误
                        Swal.fire({
                            icon: 'error',
                            title: '无法获取打印机',
                            text: data.error
                        });
                        return;
                    }
                }
                
                if (!data.printers || data.printers.length === 0) {
                    Swal.fire({
                        icon: 'error',
                        title: '未找到打印机',
                        text: '系统中未安装任何打印机，请先安装打印机驱动程序。'
                    });
                    return;
                }
                
                // 构建打印机选项
                let printerOptions = '';
                data.printers.forEach(printer => {
                    const isDefault = printer.is_default ? ' (默认)' : '';
                    const status = printer.is_ready ? '就绪' : '未就绪';
                    printerOptions += `<option value="${printer.name}" ${printer.is_default ? 'selected' : ''}>${printer.name}${isDefault} - ${status}</option>`;
                });
                
                // 显示打印设置对话框
                const result = await Swal.fire({
                    title: '打印设置',
                    html: `
                        <form id="printSettingsForm" class="text-left">
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-1">选择打印机</label>
                                <select id="printerSelect" class="w-full border border-gray-300 rounded-md shadow-sm px-3 py-2">
                                    ${printerOptions}
                                </select>
                            </div>
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-1">份数</label>
                                <input type="number" id="copies" min="1" max="10" value="1" class="w-full border border-gray-300 rounded-md shadow-sm px-3 py-2">
                            </div>
                            <div class="grid grid-cols-2 gap-4">
                                <div class="mb-4">
                                    <label class="block text-sm font-medium text-gray-700 mb-1">打印方向</label>
                                    <select id="orientation" class="w-full border border-gray-300 rounded-md shadow-sm px-3 py-2">
                                        <option value="portrait">纵向</option>
                                        <option value="landscape">横向</option>
                                    </select>
                                </div>
                                <div class="mb-4">
                                    <label class="block text-sm font-medium text-gray-700 mb-1">每页打印份数</label>
                                    <select id="pagesPerSheet" class="w-full border border-gray-300 rounded-md shadow-sm px-3 py-2">
                                        <option value="1">1</option>
                                        <option value="2">2</option>
                                        <option value="4">4</option>
                                        <option value="6">6</option>
                                        <option value="9">9</option>
                                    </select>
                                </div>
                            </div>
                        </form>
                    `,
                    showCancelButton: true,
                    confirmButtonText: '打印',
                    cancelButtonText: '取消',
                    preConfirm: () => {
                        const form = document.getElementById('printSettingsForm');
                        const selectedPrinter = form.querySelector('#printerSelect').value;
                        
                        if (!selectedPrinter) {
                            Swal.showValidationMessage('请选择打印机');
                            return false;
                        }
                        
                        return {
                            printer: selectedPrinter,
                            copies: parseInt(form.querySelector('#copies').value) || 1,
                            orientation: form.querySelector('#orientation').value,
                            pagesPerSheet: parseInt(form.querySelector('#pagesPerSheet').value) || 1
                        };
                    }
                });
                
                if (result.isConfirmed) {
                    // 显示打印中状态
                    Swal.fire({
                        title: '正在发送打印请求',
                        text: '请稍候...',
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    
                    try {
                        // 发送打印请求
                        const printResponse = await fetch('/print_file', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                filename: filename,
                                original_filename: originalFilename,
                                printer: result.value.printer,
                                settings: {
                                    copies: result.value.copies,
                                    orientation: result.value.orientation,
                                    pages_per_sheet: result.value.pagesPerSheet
                                }
                            })
                        });
                        
                        const printResult = await printResponse.json();
                        
                        if (printResult.success) {
                            Swal.fire({
                                icon: 'success',
                                title: '打印请求已提交',
                                text: printResult.message || '文件已发送到打印机，请检查打印机输出。',
                                timer: 3000,
                                timerProgressBar: true
                            });
                            
                            // 刷新文件列表以更新状态
                            setTimeout(refreshFileList, 1000);
                        } else {
                            throw new Error(printResult.message || '打印请求失败');
                        }
                    } catch (error) {
                        console.error('打印请求失败:', error);
                        
                        Swal.fire({
                            icon: 'error',
                            title: '打印失败',
                            text: error.message || '发送打印请求时出错'
                        });
                    }
                }
            } catch (error) {
                console.error('显示打印对话框失败:', error);
                
                Swal.fire({
                    icon: 'error',
                    title: '打印对话框错误',
                    text: error.message || '显示打印对话框时出错'
                });
            }
        }

        // 处理文件拖放
        function handleDrop(event) {
            event.preventDefault();
            event.stopPropagation();
            
            const dropZone = document.getElementById('dropZone');
            dropZone.classList.remove('dragover');
            
            const files = event.dataTransfer.files;
            if (files.length > 0) {
                const fileInput = document.getElementById('fileInput');
                fileInput.files = files;
                handleFileSelect({ target: fileInput });
            }
        }

        // 处理拖拽经过
        function handleDragOver(event) {
            event.preventDefault();
            event.stopPropagation();
            document.getElementById('dropZone').classList.add('dragover');
        }

        // 处理拖拽离开
        function handleDragLeave(event) {
            event.preventDefault();
            event.stopPropagation();
            document.getElementById('dropZone').classList.remove('dragover');
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    </script>
</body>
</html> 